import router, { constantRoutes } from '@/router'
import { getRouters,getCanClickMenuList } from '@/api/menu'
import { checkPermissions } from '@/api/authority_app/base'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView';

const permission = {
  state: {
    btnList: [],
    routes: [],
    addRoutes: [],
    sidebarRouters: [],
    needLoadMenu: true,
    searchMenuList: [],
  },
  mutations: {
    SET_BTN_LIST: (state, routes) => {
      state.btnList = routes
    },
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = constantRoutes.concat(routers)
    },
    SET_EMPTY_ROUTES: (state, routers) => {
      state.routes = []
    },
    SET_EMPTY_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = []
    },
    SET_SEARCH_MENU_LIST: (state, routes) => {
      state.searchMenuList = routes
    },
  },
  actions: {
    //清除路由(目前用于重新选择机构，因为这种情况没有登出但是又要改变访问权限)
    ClearRoutes( { commit } ) {
      return new Promise(resolve => {
        commit('SET_EMPTY_ROUTES', [])
        commit('SET_EMPTY_SIDEBAR_ROUTERS', [])
      });
    },
    CacheSearchMenuList( { commit } ) {
      return new Promise(resolve => {
        getCanClickMenuList().then(res => {
          if(res.result) {

            commit('SET_SEARCH_MENU_LIST', res.result)
          }
        })
      });
    },
    // 生成路由
    GenerateRoutes({ commit }) {

      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {

          if(!res)
            return;

          if(res.result) {
            for (let item of res.result) {
              if(item.meta && item.meta.title) {
                item.name = item.meta.title
              }
            }
          }
          const sdata = JSON.parse(JSON.stringify(res.result))
          const rdata = JSON.parse(JSON.stringify(res.result))

          const sidebarRoutes = filterAsyncRouter(sdata)
          const rewriteRoutes = filterAsyncRouter(rdata, false, true)
          rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', rewriteRoutes)
          commit('SET_SIDEBAR_ROUTERS', sidebarRoutes)
          resolve(rewriteRoutes)
        }).catch(res=>{
          console.log('生成路由出错')
        })
      })
    },
    //加载权限放到本地
    PutBtnList({commit,state},permissions) {

      //先去接口查询是否有这个权限
      checkPermissions(permissions).then(res => {

        let btnList = state.btnList || [];
        let hasChange = false;

        let permiResult = res.result;

        //便利查询结果
        for(let key of Object.keys(permiResult)){

          //如果有权限
          if(permiResult[key]) {

            //如果当前本地没有这一项则加入
            if(btnList.indexOf(key) < 0) {

              hasChange = true;
              btnList.push(key);
            }

          }
        }

        if(hasChange)
          commit('SET_BTN_LIST', btnList)

      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {

  return asyncRouterMap.filter(route => {

    if(!route.component || !route.path)
      return false;

    //兼容url中有参数
    if(route.path.indexOf('?') > 0) {
      let temp = route.path.split('?');
      route.path = temp[0]
      route.paramStr = temp[1]
    }

    if (type && route.children) {

      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else if (route.component === 'ParentView') {
        route.component = ParentView
      } else {
        route.component = loadView(route.component)
      }
    }

    if (route.children != null && route.children && route.children.length) {

      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {

    if (el.children && el.children.length) {
      if (el.component === 'ParentView') {

          el.children.forEach(c => {
            if(c.path) {

              c.path = el.path + '/' + c.path

              if (c.children && c.children.length) {
                children = children.concat(filterChildren(c.children, c))
                return
              }
              children.push(c)
            }
          })

        return
      }
    }
    if (lastRouter) {
      el.path = lastRouter.path + '/' + el.path
    }
    children = children.concat(el)
  })
  return children
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default permission
